package com.yueyang.sojourn.server.service.member;

import com.yueyang.sojourn.server.model.po.User;
import com.yueyang.uc.model.UcUserV1;
import com.yueyang.uc.spi.UserSpi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class UserJob {
    @Autowired
    private UserService userService;
    @Autowired
    private UserSpi userSpi;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncUserJob() {
        log.info("定时任务 同步uc用户 开始");
        this.syncFromUc();
        log.info("定时任务 同步uc用户 结束");
    }

    /**
     * 从uc同步用户
     */
    public void syncFromUc() {
        // 一次获取500个
        int pageSize = 100;
        Long newestUserId = 0L;
        User newest = this.userService.findNewest();
        if (newest != null) {
            newestUserId = newest.getUserId();
        }

        List<UcUserV1> ucUserV1List = null;
        do {
            ucUserV1List = userSpi.findNewestUserIds(newestUserId, pageSize);
            List<User> userList = new ArrayList<>();
            ucUserV1List.stream().forEach(ucUserV1 -> {
                User user = new User();
                user.setRegTime(ucUserV1.getCtime());
                user.setUserId(ucUserV1.getId());
                BeanUtils.copyProperties(ucUserV1, user);
                user.setCtime(new Date());
                user.setMtime(new Date());
                userList.add(user);
            });
            if (CollectionUtils.isNotEmpty(userList)) {
                this.userService.batchInsert(userList);
                newestUserId = userList.get(userList.size() - 1).getUserId();
            }
        } while (ucUserV1List.size() >= pageSize);
    }
}
